<template>
  <div class="coding-challenge">
    <div class="game-header">
      <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
      <div class="game-title">
        <h1>🎯 编程挑战赛</h1>
        <p>通过编写代码解决实际问题，提升编程能力</p>
      </div>
      <div class="game-stats">
        <el-statistic title="当前积分" :value="gameStats.points" />
        <el-statistic title="完成题目" :value="`${gameStats.completed}/${challenges.length}`" />
      </div>
    </div>

    <!-- 难度选择 -->
    <el-tabs v-model="activeDifficulty" class="difficulty-tabs">
      <el-tab-pane label="🟢 简单" name="easy" />
      <el-tab-pane label="🟡 中等" name="medium" />
      <el-tab-pane label="🔴 困难" name="hard" />
    </el-tabs>

    <!-- 挑战列表 -->
    <div class="challenges-list">
      <div 
        v-for="challenge in filteredChallenges" 
        :key="challenge.id"
        class="challenge-card"
        :class="{ completed: challenge.completed }"
        @click="startChallenge(challenge)"
      >
        <div class="challenge-header">
          <div class="challenge-title">
            <h3>{{ challenge.title }}</h3>
            <el-tag :type="getDifficultyType(challenge.difficulty)" size="small">
              {{ challenge.difficulty }}
            </el-tag>
          </div>
          <div class="challenge-points">
            <el-icon><Trophy /></el-icon>
            {{ challenge.points }} 积分
          </div>
        </div>
        <p class="challenge-desc">{{ challenge.description }}</p>
        <div class="challenge-footer">
          <div class="challenge-tags">
            <el-tag v-for="tag in challenge.tags" :key="tag" size="small" effect="plain">
              {{ tag }}
            </el-tag>
          </div>
          <div class="challenge-stats">
            <span>
              <el-icon><User /></el-icon>
              {{ challenge.attempts }} 次尝试
            </span>
            <span>
              <el-icon><Check /></el-icon>
              通过率: {{ challenge.passRate }}%
            </span>
          </div>
        </div>
        <el-icon v-if="challenge.completed" class="completed-icon"><CircleCheck /></el-icon>
      </div>
    </div>

    <!-- 编程挑战对话框 -->
    <el-dialog
      v-model="showCodingDialog"
      :title="currentChallenge?.title"
      width="90%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <div class="coding-editor">
        <div class="editor-sidebar">
          <h3>题目描述</h3>
          <div class="problem-description">
            <p>{{ currentChallenge?.problemStatement }}</p>
            
            <h4>输入说明：</h4>
            <p>{{ currentChallenge?.inputDesc }}</p>
            
            <h4>输出说明：</h4>
            <p>{{ currentChallenge?.outputDesc }}</p>
            
            <h4>示例：</h4>
            <div v-for="(example, index) in currentChallenge?.examples" :key="index" class="example">
              <div><strong>输入：</strong><code>{{ example.input }}</code></div>
              <div><strong>输出：</strong><code>{{ example.output }}</code></div>
            </div>
          </div>
          
          <h3>测试用例</h3>
          <div class="test-cases">
            <div v-for="(testCase, index) in testResults" :key="index" class="test-case" :class="testCase.status">
              <span>测试 {{ index + 1 }}</span>
              <el-icon v-if="testCase.status === 'passed'"><CircleCheck /></el-icon>
              <el-icon v-else-if="testCase.status === 'failed'"><CircleClose /></el-icon>
              <el-icon v-else><Clock /></el-icon>
            </div>
          </div>
        </div>

        <div class="editor-main">
          <div class="editor-header">
            <el-select v-model="selectedLanguage" placeholder="选择语言">
              <el-option label="JavaScript" value="javascript" />
              <el-option label="Python" value="python" />
              <el-option label="Java" value="java" />
              <el-option label="C++" value="cpp" />
            </el-select>
            
            <div class="editor-actions">
              <el-button @click="runCode" :loading="isRunning">
                <el-icon><CaretRight /></el-icon>
                运行代码
              </el-button>
              <el-button type="primary" @click="submitCode" :loading="isSubmitting">
                <el-icon><Upload /></el-icon>
                提交答案
              </el-button>
            </div>
          </div>

          <div class="code-editor">
            <el-input
              v-model="userCode"
              type="textarea"
              :rows="20"
              placeholder="在这里编写你的代码..."
              spellcheck="false"
            />
          </div>

          <div class="output-panel">
            <h4>运行结果：</h4>
            <div class="console-output" :class="outputType">
              <pre v-if="codeOutput">{{ codeOutput }}</pre>
              <p v-else class="placeholder">点击"运行代码"查看结果</p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, Trophy, User, Check, CircleCheck, CircleClose,
  Clock, CaretRight, Upload
} from '@element-plus/icons-vue'

const router = useRouter()

// 游戏统计
const gameStats = ref({
  points: 320,
  completed: 5
})

// 当前难度
const activeDifficulty = ref('easy')

// 挑战列表
const challenges = ref([
  {
    id: 1,
    title: '两数之和',
    description: '给定一个整数数组和一个目标值，找出数组中和为目标值的两个数',
    difficulty: '简单',
    points: 50,
    attempts: 1234,
    passRate: 78,
    tags: ['数组', '哈希表'],
    completed: true,
    problemStatement: '给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出和为目标值 target 的那两个整数，并返回它们的数组下标。',
    inputDesc: '一个整数数组 nums 和一个整数 target',
    outputDesc: '返回两个数的下标数组',
    examples: [
      { input: 'nums = [2,7,11,15], target = 9', output: '[0,1]' },
      { input: 'nums = [3,2,4], target = 6', output: '[1,2]' }
    ]
  },
  {
    id: 2,
    title: '反转字符串',
    description: '编写一个函数，将输入的字符串反转过来',
    difficulty: '简单',
    points: 40,
    attempts: 2345,
    passRate: 92,
    tags: ['字符串', '双指针'],
    completed: true,
    problemStatement: '编写一个函数，其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。',
    inputDesc: '一个字符数组 s',
    outputDesc: '原地修改输入数组，不需要返回值',
    examples: [
      { input: 's = ["h","e","l","l","o"]', output: '["o","l","l","e","h"]' }
    ]
  },
  {
    id: 3,
    title: '回文数判断',
    description: '判断一个整数是否是回文数',
    difficulty: '简单',
    points: 45,
    attempts: 1890,
    passRate: 85,
    tags: ['数学', '字符串'],
    completed: false,
    problemStatement: '给你一个整数 x ，如果 x 是一个回文整数，返回 true ；否则，返回 false 。',
    inputDesc: '一个整数 x',
    outputDesc: '返回布尔值',
    examples: [
      { input: 'x = 121', output: 'true' },
      { input: 'x = -121', output: 'false' }
    ]
  },
  {
    id: 4,
    title: '合并两个有序数组',
    description: '将两个有序数组合并成一个有序数组',
    difficulty: '中等',
    points: 80,
    attempts: 3456,
    passRate: 65,
    tags: ['数组', '双指针', '排序'],
    completed: true,
    problemStatement: '给你两个按非递减顺序排列的整数数组 nums1 和 nums2，另有两个整数 m 和 n ，分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中，使合并后的数组同样按非递减顺序排列。',
    inputDesc: '两个有序数组 nums1, nums2 和它们的长度 m, n',
    outputDesc: '原地修改 nums1',
    examples: [
      { input: 'nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3', output: '[1,2,2,3,5,6]' }
    ]
  },
  {
    id: 5,
    title: '最长公共前缀',
    description: '查找字符串数组中的最长公共前缀',
    difficulty: '中等',
    points: 75,
    attempts: 2789,
    passRate: 70,
    tags: ['字符串', '分治'],
    completed: false,
    problemStatement: '编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀，返回空字符串 ""。',
    inputDesc: '一个字符串数组 strs',
    outputDesc: '返回最长公共前缀字符串',
    examples: [
      { input: 'strs = ["flower","flow","flight"]', output: '"fl"' },
      { input: 'strs = ["dog","racecar","car"]', output: '""' }
    ]
  },
  {
    id: 6,
    title: '二叉树的最大深度',
    description: '计算二叉树的最大深度',
    difficulty: '困难',
    points: 120,
    attempts: 4567,
    passRate: 58,
    tags: ['树', '深度优先搜索', '递归'],
    completed: false,
    problemStatement: '给定一个二叉树，找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。',
    inputDesc: '二叉树的根节点 root',
    outputDesc: '返回最大深度整数',
    examples: [
      { input: 'root = [3,9,20,null,null,15,7]', output: '3' }
    ]
  },
  {
    id: 7,
    title: '动态规划 - 爬楼梯',
    description: '计算爬到楼顶的方法数',
    difficulty: '困难',
    points: 150,
    attempts: 2345,
    passRate: 45,
    tags: ['动态规划', '数学'],
    completed: false,
    problemStatement: '假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢？',
    inputDesc: '一个正整数 n',
    outputDesc: '返回爬楼梯的方法数',
    examples: [
      { input: 'n = 2', output: '2' },
      { input: 'n = 3', output: '3' }
    ]
  }
])

// 当前挑战
const currentChallenge = ref(null)
const showCodingDialog = ref(false)
const selectedLanguage = ref('javascript')
const userCode = ref('')
const codeOutput = ref('')
const outputType = ref('')
const isRunning = ref(false)
const isSubmitting = ref(false)

// 测试结果
const testResults = ref([
  { status: 'pending' },
  { status: 'pending' },
  { status: 'pending' },
  { status: 'pending' }
])

// 过滤挑战
const filteredChallenges = computed(() => {
  return challenges.value.filter(c => c.difficulty === getDifficultyText(activeDifficulty.value))
})

const getDifficultyText = (difficulty) => {
  const map = { easy: '简单', medium: '中等', hard: '困难' }
  return map[difficulty] || '简单'
}

const getDifficultyType = (difficulty) => {
  const map = { '简单': 'success', '中等': 'warning', '困难': 'danger' }
  return map[difficulty] || 'info'
}

// 返回
const goBack = () => {
  router.push('/learning/games/center')
}

// 开始挑战
const startChallenge = (challenge) => {
  currentChallenge.value = challenge
  showCodingDialog.value = true
  
  // 加载模板代码
  const templates = {
    javascript: `function solve(input) {\n  // 在这里编写你的代码\n  \n  return result;\n}`,
    python: `def solve(input):\n    # 在这里编写你的代码\n    \n    return result`,
    java: `public class Solution {\n    public static void solve(String input) {\n        // 在这里编写你的代码\n        \n        return result;\n    }\n}`,
    cpp: `#include <iostream>\nusing namespace std;\n\nint solve(string input) {\n    // 在这里编写你的代码\n    \n    return result;\n}`
  }
  userCode.value = templates[selectedLanguage.value]
  codeOutput.value = ''
  testResults.value = testResults.value.map(() => ({ status: 'pending' }))
}

// 运行代码
const runCode = async () => {
  if (!userCode.value.trim()) {
    ElMessage.warning('请先编写代码')
    return
  }

  isRunning.value = true
  codeOutput.value = '正在运行...'
  outputType.value = ''

  // 模拟代码运行
  setTimeout(() => {
    codeOutput.value = `执行成功！\n\n示例输入: ${currentChallenge.value.examples[0].input}\n预期输出: ${currentChallenge.value.examples[0].output}\n实际输出: ${currentChallenge.value.examples[0].output}\n\n✅ 运行通过`
    outputType.value = 'success'
    isRunning.value = false
    ElMessage.success('代码运行成功！')
  }, 1500)
}

// 提交代码
const submitCode = async () => {
  if (!userCode.value.trim()) {
    ElMessage.warning('请先编写代码')
    return
  }

  isSubmitting.value = true

  // 模拟测试
  for (let i = 0; i < testResults.value.length; i++) {
    await new Promise(resolve => setTimeout(resolve, 500))
    testResults.value[i].status = Math.random() > 0.2 ? 'passed' : 'failed'
  }

  isSubmitting.value = false

  const passedCount = testResults.value.filter(t => t.status === 'passed').length
  const totalCount = testResults.value.length

  if (passedCount === totalCount) {
    // 全部通过
    ElMessageBox.alert(
      `🎉 恭喜！所有测试用例通过！\n\n获得 ${currentChallenge.value.points} 积分`,
      '提交成功',
      {
        confirmButtonText: '太棒了',
        callback: () => {
          currentChallenge.value.completed = true
          gameStats.value.points += currentChallenge.value.points
          gameStats.value.completed += 1
          showCodingDialog.value = false
        }
      }
    )
  } else {
    ElMessage.error(`测试未全部通过 (${passedCount}/${totalCount})，请检查代码`)
  }
}
</script>

<style scoped>
.coding-challenge {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.game-header {
  display: flex;
  align-items: center;
  gap: 30px;
  margin-bottom: 30px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
}

.game-title {
  flex: 1;
}

.game-title h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
}

.game-title p {
  margin: 0;
  opacity: 0.9;
}

.game-stats {
  display: flex;
  gap: 40px;
}

.game-stats :deep(.el-statistic__head) {
  color: rgba(255, 255, 255, 0.8);
}

.game-stats :deep(.el-statistic__content) {
  color: white;
  font-weight: bold;
}

.difficulty-tabs {
  margin-bottom: 30px;
}

.challenges-list {
  display: grid;
  gap: 20px;
}

.challenge-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.challenge-card:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.challenge-card.completed {
  border-left: 4px solid #67c23a;
}

.challenge-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.challenge-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.challenge-title h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.challenge-points {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #e6a23c;
  font-weight: bold;
}

.challenge-desc {
  color: #606266;
  margin-bottom: 16px;
}

.challenge-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.challenge-tags {
  display: flex;
  gap: 8px;
}

.challenge-stats {
  display: flex;
  gap: 16px;
  color: #909399;
  font-size: 13px;
}

.challenge-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.completed-icon {
  position: absolute;
  top: 24px;
  right: 24px;
  font-size: 32px;
  color: #67c23a;
}

/* 编程编辑器 */
.coding-editor {
  display: grid;
  grid-template-columns: 400px 1fr;
  gap: 20px;
  height: 70vh;
}

.editor-sidebar {
  overflow-y: auto;
  padding-right: 12px;
}

.editor-sidebar h3 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
}

.problem-description {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 14px;
  line-height: 1.6;
}

.problem-description h4 {
  margin: 16px 0 8px 0;
  font-size: 14px;
  color: #606266;
}

.example {
  background: white;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.example code {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
}

.test-cases {
  display: grid;
  gap: 8px;
}

.test-case {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
  font-size: 14px;
}

.test-case.passed {
  background: #f0f9ff;
  color: #67c23a;
  border-left: 3px solid #67c23a;
}

.test-case.failed {
  background: #fef0f0;
  color: #f56c6c;
  border-left: 3px solid #f56c6c;
}

.editor-main {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-actions {
  display: flex;
  gap: 12px;
}

.code-editor {
  flex: 1;
  min-height: 0;
}

.code-editor :deep(textarea) {
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 14px;
  line-height: 1.6;
  resize: none;
}

.output-panel {
  border-top: 1px solid #dcdfe6;
  padding-top: 12px;
}

.output-panel h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #606266;
}

.console-output {
  background: #1e1e1e;
  color: #d4d4d4;
  padding: 16px;
  border-radius: 6px;
  min-height: 100px;
  max-height: 200px;
  overflow-y: auto;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
}

.console-output.success {
  border-left: 4px solid #67c23a;
}

.console-output.error {
  border-left: 4px solid #f56c6c;
}

.console-output pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.console-output .placeholder {
  color: #909399;
  text-align: center;
  margin: 30px 0;
}
</style>

